package com.redisson.demo.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StockController {

    @Autowired
    private Redisson redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 模拟减库存
     *
     * @return ""
     */
    @GetMapping("/detuck_stock")
    public String detuckStock() {
        String lockKey = "lockKey";
        // 获取到redisson锁对象
        RLock redissonLock = redisson.getLock(lockKey);
        try {
            // ========= 添加redisson锁并实现锁续命功能 =============
            /**
             *  主要执行一下几个操作
             *
             *  1、将localKey设置到Redis服务器上，默认过期时间是30s
             *  2、每10s触发一次锁续命功能
             */
            redissonLock.lock();

            // ======== 扣减库存业务开始 ============
            // 从redis获取库存数量
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            // 如果库存数量大于0
            if (stock > 0) {
                int realStock = stock - 1;
                // 相当于jedis.set(key, value)
                stringRedisTemplate.opsForValue().set("stock", realStock + "");
                System.out.println(Thread.currentThread().getId() + "---扣减成功，剩余库存：" + realStock + "");
            } else {
                // 如果库存数量小于0
                System.out.println(Thread.currentThread().getId() + "扣减失败，库存不足！");
            }
            // ======== 扣减库存业务结束 ============
        } finally {
            // 防止异常导致锁无法释放！！！
            // ============= 释放redisson锁 ==========
            redissonLock.unlock();
        }

        return "end";
    }
}